<template>
  <div class="page-wrap1">
    <div class="card">
      <div class="icon-top"></div>
      <div class="card-content com-head-wrap1">
        <div class="card-data">
          <div class="card-item">
            <div class="iconfont icon-user"></div>
            <div class="title">用户账号</div>
            <div class="card-value">
              {{ data.detailData ? data.detailData.accountNumber : '--' }}
            </div>
          </div>
          <div class="card-item">
            <div class="iconfont icon-card"></div>
            <div class="title">用户姓名</div>
            <div class="card-value">
              {{ data.detailData ? data.detailData.accountName : '--' }}
            </div>
          </div>
          <div class="card-item">
            <div class="iconfont icon-enterprise"></div>
            <div class="title">企业钱包</div>
            <div class="card-value">
              ￥{{ data.detailData ? data.detailData.unitBalance : '--' }}
            </div>
          </div>
          <div class="card-item">
            <div class="iconfont icon-wallet1"></div>
            <div class="title">个人钱包</div>
            <div class="card-value">
              ￥{{ data.detailData ? data.detailData.personalBalance : '--' }}
            </div>
          </div>
        </div>
      </div>
      <div class="card-content1">
        <div class="button-list">
          <el-button
            v-if="bntAuth(`${key}.change`)"
            type="primary"
            plain
            class="button-item"
            @click="show"
            :disabled="orgType !== 'CHANNEL'"
          >
            <div class="iconfont icon-correct"></div>
            余额修正</el-button
          >
          <el-button type="primary" plain class="button-item" @click="back">
            <div class="iconfont icon-back"></div>
            返回</el-button
          >
        </div>
      </div>
      <div class="icon-bottom"></div>
    </div>
    <el-tabs
      v-if="data.detailData.id"
      v-model="data.activeTab"
      class="demo-tabs"
      @tab-click="handleClickTab"
    >
      <el-tab-pane label="钱包流水" name="flow">
        <Table
          v-if="data.activeTab === 'flow'"
          ref="tableFlowRef"
          :columns="flow.columns"
          :toolbar="flow.toolbar"
          :query="flow.query"
          @get-list="getFlow"
        ></Table>
      </el-tab-pane>
      <el-tab-pane label="月账单" name="month"
        ><Table
          v-if="data.activeTab === 'month'"
          ref="tableMonthRef"
          :columns="month.columns"
          :toolbar="month.toolbar"
          :query="month.query"
          @get-list="getMonth"
        ></Table
      ></el-tab-pane>
      <el-tab-pane label="退款申请" name="refund"
        ><Table
          v-if="data.activeTab === 'refund'"
          ref="tableRefundRef"
          :columns="refund.columns"
          :toolbar="refund.toolbar"
          @get-list="getRefund"
        ></Table
      ></el-tab-pane>
      <el-tab-pane label="优惠券明细" name="coupon">
        <Table
          v-if="data.activeTab === 'coupon'"
          ref="tableCouponRef"
          :columns="coupon.columns"
          :handles="coupon.handles"
          :query="coupon.query"
          @get-list="getCoupon"
        ></Table>
      </el-tab-pane>
    </el-tabs>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="余额修正"
      width="430"
      class="qc-custom-dialog"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="110px"
        class="dialog-form-wrap"
      >
        <el-form-item label="钱包类型" prop="paymentType">
          <el-radio-group
            v-model="ruleForm.paymentType"
            v-for="(item, index) in optionsS.paymentType"
            :key="index"
            :disabled="Boolean(key === 'noEnterpriseUserList')"
          >
            <el-radio :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="修正金额" prop="amount" class="has-tips">
          <el-input
            v-model.trim="ruleForm.amount"
            placeholder="请输入修正金额，精确至0.01"
            maxlength="30"
            clearable
          />
          <div class="tip">
            <div class="icon"></div>
            输入正数，余额增加；输入负值，余额减少。
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model.trim="ruleForm.remark"
            placeholder="请输入备注"
            maxlength="200"
            type="textarea"
            :rows="3"
            show-word-limit
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="hide">取消</el-button>
          <el-button type="primary" v-btnAntiShake="onSubmit"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
    <DialogDetailVoided
      ref="dialogDetailVoidedRef"
      @get-data="getCouponData"
    ></DialogDetailVoided>
  </div>
</template>

<script lang="ts" setup>
import Table from '@/components/table/index.vue';
import DialogDetailVoided from '@/pages/marketingManagement/couponManagement/coupon/dialogDetailVoided.vue';
import {
  getAccount,
  pagingAccountFlow,
  changeAccount,
} from '@/service/apis/enterprise';
import {
  pagingMonthAccountFlow,
  pagingRefundRequest,
  EXPORT_PERSONALFLOW,
  EXPORT_MONTHACCOUNTFLOW,
  EXPORT_REFUNDREQUEST,
} from '@/service/apis/user';
import { queryDicByParent } from '@/service/apis/api';
import { pagingEntity } from '@/service/apis/market';
import { FormInstance, FormRules } from 'element-plus';
import { IS_DECIMAL_2_1 } from '@/utils/verify';
import { getYM, bntAuth, exportFile } from '@/utils/utils';

const router = useRouter();
const route = useRoute();
const {
  query: { id, key },
} = route;

const tableFlowRef = ref();
const tableMonthRef = ref();
const tableRefundRef = ref();
const tableCouponRef = ref();
const ruleFormRef = ref<FormInstance>();
const dialogDetailVoidedRef = ref();

const orgType = window.localStorage.getItem('orgType');

const optionsS = reactive({
  paymentType: [] as any,
});

queryDicByParent({
  listDtos: [
    'accountFlowType',
    'paymentType',
    'couponType',
    'couponEntityStatus',
    'expireStatus',
  ],
}).then((res: any) => {
  if (res) {
    console.log('ddd--', res);
    flow.query[0].props.options = res.accountFlowType.filter(
      (item: any) => item.value !== '8' && item.value !== '9'
    );
    console.log('ddd--', flow.query[0].props.options);
    flow.columns[1].dic = [...res.accountFlowType];
    flow.query[1].props.options = [...res.paymentType];
    flow.columns[3].dic = [...res.paymentType];
    optionsS.paymentType = [...res.paymentType];
    month.columns[1].dic = [...res.accountFlowType];
    coupon.columns[1].dic = [...res.couponType];
    coupon.columns[4].dic = [...res.couponEntityStatus];
    coupon.columns[5].dic = [...res.expireStatus];
    coupon.query[0].props.options = [...res.couponEntityStatus];
    coupon.query[1].props.options = [...res.couponType];
  }
});

let dialogVisible = ref(false);
const ruleForm = reactive({
  accountId: '',
  paymentType: '0',
  amount: '',
  remark: '',
  type: '5',
});
const rules = reactive<FormRules>({
  paymentType: [
    { required: true, message: '请选择钱包类型', trigger: ['blur', 'change'] },
  ],
  amount: [
    { required: true, message: '请输入修正金额', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_2_1,
      message: '请输入正确的修正金额，保留2位小数',
      trigger: 'blur',
    },
  ],
  remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
});
// 关闭弹框
const hide = () => {
  dialogVisible.value = false;
};
// 打开弹窗并赋值
const show = () => {
  dialogVisible.value = true;
  ruleForm.amount = '';
  ruleForm.remark = '';
  ruleForm.paymentType = '0';
  nextTick(() => {
    ruleFormRef.value?.clearValidate();
  });
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  console.log('submit---', ruleForm);
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid, fields: any) => {
    if (valid) {
      ruleForm.accountId = data?.detailData?.id;
      changeAccount(ruleForm).then((res: any) => {
        console.log('res===', res);
        emit('clear-cache');
        hide();
        getAccountData();
        if (data.activeTab === 'flow') {
          tableFlowRef.value?.handleQuery();
        }
      });
    } else {
      for (const key in ruleForm) {
        if (fields[key]) {
          ruleFormRef.value?.scrollToField(key);
          break;
        }
      }
    }
  });
};

const flow = reactive({
  columns: [
    {
      prop: 'billId',
      label: '流水号',
    },
    {
      prop: 'type',
      label: '流水类型',
      dic: [] as any,
      type: Number,
    },
    {
      prop: 'amount',
      label: '流水金额（元）',
    },
    {
      prop: 'paymentType',
      label: '支付钱包',
      dic: [] as any,
      type: Number,
    },
    {
      prop: 'orderId',
      label: '关联订单(充电/充值)',
    },
    {
      prop: 'remark',
      label: '备注',
    },
    {
      prop: 'createBy',
      label: '执行人',
    },
    {
      prop: 'createTime',
      label: '流水时间',
    },
  ],
  toolbar: [
    {
      label: '导出',
      permission: `${key}.export`,
      icon: 'icon-export',
      type: 'primary',
      plain: true,
      handle: (row: any) => {
        console.log('导出---', row);
        let form: any = { ...tableFlowRef.value?.getForm() };
        form.accountId = data.detailData?.id;
        if (form.time) {
          form.startTime = form.time[0];
          form.endTime = form.time[1];
        }
        delete form.time;
        exportFile(
          EXPORT_PERSONALFLOW,
          `${data.detailData.accountNumber}-钱包流水`,
          form
        );
      },
    },
  ],
  query: [
    {
      label: '流水类型',
      prop: 'type',
      comName: 'select',
      props: {
        placeholder: '请选择流水类型',
        options: [] as any,
      },
    },
    {
      label: '支付钱包',
      prop: 'paymentType',
      comName: 'select',
      props: {
        placeholder: '请选择支付钱包',
        options: [] as any,
      },
    },
    {
      label: '关联订单',
      prop: 'orderId',
      comName: 'input',
      props: {
        placeholder: '请输入关联订单',
      },
    },
    {
      label: '流水时间',
      prop: 'time',
      comName: 'date',
      keys: ['startTime', 'endTime'],
      props: {
        type: 'daterange',
      },
    },
  ],
});
const month = reactive({
  columns: [
    {
      prop: 'orderId',
      label: '订单号',
    },
    {
      prop: 'type',
      label: '消费类型',
      dic: [] as any,
      type: Number,
    },
    {
      prop: 'amount',
      label: '消费金额（元）',
    },
    {
      prop: 'createTime',
      label: '消费时间',
    },
  ],
  toolbar: [
    {
      label: '导出',
      permission: `${key}.export`,
      icon: 'icon-export',
      type: 'primary',
      plain: true,
      handle: (row: any) => {
        console.log('导出---', row);
        let form: any = { ...tableMonthRef.value?.getForm() };
        form.accountId = data.detailData?.id;
        exportFile(
          EXPORT_MONTHACCOUNTFLOW,
          `${data.detailData.accountNumber}-${form.month}-月账单`,
          form
        );
      },
    },
  ],
  query: [
    {
      label: '流水时间',
      prop: 'month',
      comName: 'date',
      value: getYM(),
      props: {
        type: 'month',
        clearable: '1',
      },
    },
  ],
});
const refund = reactive({
  columns: [
    {
      prop: 'createTime',
      label: '申请时间',
      width: 150,
    },
    {
      prop: 'requestAmount',
      label: '申请金额（元）',
      width: 120,
    },
    {
      prop: 'receivedAmount',
      label: '已到账金额（元）',
      width: 130,
    },
    {
      prop: 'status',
      label: '退款状态',
    },
    {
      prop: 'details',
      label: '退款明细',
      width: 850,
      template: (row: any, index: number) => {
        const detail = row.details;
        let str = '';
        const sp = '<span style="margin: 0 6px;"></span>';
        detail.forEach((item: any) => {
          str += `<div>退款金额：${item.settlementRefund || '--'}元${sp}状态：${
            item.status || '--'
          }${sp}渠道：${item.channel || '--'}${sp}充值订单：${
            item.transactionId || '--'
          }${sp}退款订单：${item.refundId || '--'}</div>`;
        });
        return str;
      },
    },
  ],
  toolbar: [
    {
      label: '导出',
      permission: `${key}.export`,
      icon: 'icon-export',
      type: 'primary',
      plain: true,
      handle: (row: any) => {
        console.log('导出---', row);
        exportFile(
          EXPORT_REFUNDREQUEST,
          `${data.detailData.accountNumber}-退款申请`,
          data.detailData?.id
        );
      },
    },
  ],
});
const coupon = reactive({
  columns: [
    {
      prop: 'couponName',
      label: '优惠券名称',
    },
    {
      prop: 'couponType',
      label: '优惠券种类',
      dic: [] as any,
      type: Number,
    },
    {
      prop: 'discountAmount',
      label: '面额/折扣',
      template: (row: any, index: number) => {
        return row.couponType === 1
          ? `${row.discountAmount}元`
          : `${row.discountRatio}%`;
      },
    },
    {
      prop: 'couponNumber',
      label: '优惠券编号',
    },
    {
      prop: 'status',
      label: '使用状态',
      dic: [] as any,
      type: Number,
    },
    {
      prop: 'expireStatus',
      label: '是否过期',
      dic: [] as any,
      type: Number,
    },
    {
      prop: 'relName',
      label: '关联活动/任务',
    },
    {
      prop: 'createTime',
      label: '发放时间',
    },
    {
      prop: 'writeOffTime',
      label: '核销时间',
    },
    {
      prop: 'orderId',
      label: '关联订单',
    },
    {
      prop: 'remark',
      label: '备注',
    },
  ],
  handles: [
    {
      label: '作废',
      permission: `${key}.cancel`,
      disabledFun: (row: any) => {
        return row.status !== 0 || row.expireStatus !== 0;
      },
      handle: (row: any) => {
        console.log('作废 ---', row);
        dialogDetailVoidedRef.value?.show(1, row.id);
      },
    },
  ],
  query: [
    {
      label: '使用状态',
      prop: 'status',
      comName: 'select',
      value: '0',
      props: {
        placeholder: '请选择使用状态',
        options: [] as any,
      },
    },
    {
      label: '优惠券种类',
      prop: 'couponType',
      comName: 'select',
      props: {
        placeholder: '请选择优惠券种类',
        change: (value: any) => {
          console.log(value);
        },
        options: [] as any,
      },
    },
    {
      label: '关联活动',
      prop: 'relName',
      comName: 'input',
      props: {
        placeholder: '请输入关联活动',
      },
    },
    {
      label: '发放时间',
      prop: 'time',
      comName: 'date',
      keys: ['startTime', 'startTime'],
      props: {
        type: 'daterange',
      },
    },
  ],
});

// 获取用户信息
const getAccountData = () => {
  getAccount({
    originalAccountId: id,
    // originalAccountId: '1651414425581502465',
    accountType: '0',
  }).then((res: any) => {
    if (res) {
      data.detailData = res;
    }
  });
};
getAccountData();

//钱包流水
const getFlow = (page: any, search: any) => {
  nextTick(() => {
    let form: any = { ...search.ruleForm };
    form.accountId = data.detailData?.id;
    if (form.time) {
      form.startTime = form.time[0];
      form.endTime = form.time[1];
    }
    delete form.time;
    pagingAccountFlow(form, page).then((res: any) => {
      if (res) {
        if (
          page.pageNo !== 1 &&
          (!res.dataList || res.dataList?.length === 0)
        ) {
          page.pageNo--;
          getFlow(page, search);
          return;
        }
        nextTick(() => {
          tableFlowRef.value?.setTable({
            total: res.totalCount,
            table: res.dataList,
          });
        });
      }
    });
  });
};

//月账单
const getMonth = (page: any, search: any) => {
  const form = { ...search.ruleForm };
  form.accountId = data.detailData?.id;
  pagingMonthAccountFlow(form, page).then((res: any) => {
    if (res) {
      if (page.pageNo !== 1 && (!res.dataList || res.dataList?.length === 0)) {
        page.pageNo--;
        getMonth(page, search);
        return;
      }
      nextTick(() => {
        tableMonthRef.value?.setTable({
          total: res.totalCount,
          table: res.dataList,
        });
      });
    }
  });
};

//退款申请
const getRefund = (page: any, search: any) => {
  pagingRefundRequest(data.detailData?.id, page).then((res: any) => {
    if (res) {
      if (page.pageNo !== 1 && (!res.dataList || res.dataList?.length === 0)) {
        page.pageNo--;
        getRefund(page, search);
        return;
      }
      nextTick(() => {
        tableRefundRef.value?.setTable({
          total: res.totalCount,
          table: res.dataList,
        });
      });
    }
  });
};

//优惠券明细
const getCoupon = (page: any, search: any) => {
  const form = { ...search.ruleForm };
  if (form.time) {
    form.startTime = form.time[0];
    form.endTime = form.time[1];
    delete form.time;
  }
  form.userId = id;
  pagingEntity(form, page).then((res: any) => {
    if (res) {
      if (page.pageNo !== 1 && (!res.dataList || res.dataList?.length === 0)) {
        page.pageNo--;
        getCoupon(page, search);
        return;
      }
      nextTick(() => {
        tableCouponRef.value?.setTable({
          total: res.totalCount,
          table: res.dataList,
        });
      });
    }
  });
};
const getCouponData = () => {
  tableCouponRef.value?.getData();
};
let data = reactive({
  detailData: {} as any,
  activeTab: 'flow',
});

const handleClickTab = (e: any) => {};

const back = () => {
  router.go(-1);
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/head.scss';
</style>
<style lang="scss" scoped>
.card {
  .card-content {
    width: 80%;
  }
  .card-content1 {
    display: flex;
    justify-content: center;
    width: 20%;
    .button-list {
      display: flex;
      flex-direction: column;
      align-content: center;
      .button-item {
        width: 104px;
        margin: 17px 0 0 0;
        font-size: 13px;
        border-radius: 8px;
        border: 0;

        &:first-child {
          margin: 0;
        }
        .iconfont {
          padding-right: 4px;
        }
      }
    }
  }
}
</style>